package com.jacobson.huobi.utils

import android.content.Context
import android.content.Intent
import android.os.Build
import com.jacobson.core.widget.logger.LoggerFactory
import com.jacobson.huobi.Constants
import com.jacobson.huobi.HuobiApplication
import com.jacobson.huobi.mvp.OnePXActivity
import com.jacobson.huobi.services.KeepAliveService

object KeepLiveManager {
    private val logger = LoggerFactory.getLogger(KeepLiveManager::class.java)
    /** 启动前台保活服务 */
    fun startForegroundService() {
        logger.d("start foreground keep alive service!")
        val context = HuobiApplication.getInstance()
        val intent = Intent(context, KeepAliveService::class.java)
        intent.`package` = context.packageName
        intent.action = Constants.ACTION_KEEP_ALIVE_SERVICE
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(intent)
        } else {
            context.startService(intent)
        }
    }

    /** 停止前台保活服务 */
    fun stopForegroundService() {
        logger.d("stop foreground keep alive service!")
        val context = HuobiApplication.getInstance()
        val intent = Intent(context, KeepAliveService::class.java)
        intent.`package` = context.packageName
        intent.action = Constants.ACTION_KEEP_ALIVE_SERVICE
        context.stopService(intent)
    }

    /** 启动单像素界面 */
    fun startOnePxActivity(context: Context) {
        logger.d("系统锁屏，启动1像素保活...")
        val intent = Intent(context, OnePXActivity::class.java)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        context.startActivity(intent)
    }

    fun finishOnePxActivity() {
        HuobiApplication.onePxActivity?.takeIf { !it.isDestroyed }?.finish()
    }

    fun storeOnePxActivity(onePXActivity: OnePXActivity) {
        finishOnePxActivity()
        HuobiApplication.onePxActivity = onePXActivity
    }
}